#!/usr/bin/env python3
"""
活动表结构升级脚本
添加新的字段以支持更丰富的活动功能

执行方式：
python migrations/upgrade_activity_table.py
"""

import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from sqlalchemy import text

def upgrade_activity_table():
    """升级活动表结构"""
    
    app = create_app()
    
    with app.app_context():
        try:
            # 检查表是否存在
            result = db.session.execute(text("SHOW TABLES LIKE 'activities'")).fetchone()
            if not result:
                print("活动表不存在，请先运行基础迁移")
                return False
            
            # 获取当前表结构
            columns = db.session.execute(text("DESCRIBE activities")).fetchall()
            existing_columns = [col[0] for col in columns]
            
            print(f"当前活动表字段: {existing_columns}")
            
            # 需要添加的字段
            new_columns = [
                ("registration_deadline", "DATETIME", "报名截止时间"),
                ("min_participants", "INT DEFAULT 1", "最少参与人数"),
                ("activity_type", "VARCHAR(50)", "活动类型"),
                ("tags", "TEXT", "活动标签"),
                ("is_free", "BOOLEAN DEFAULT TRUE", "是否免费"),
                ("fee", "DECIMAL(10,2) DEFAULT 0", "活动费用"),
                ("fee_description", "TEXT", "费用说明"),
                ("need_approval", "BOOLEAN DEFAULT FALSE", "是否需要审核"),
                ("allow_waitlist", "BOOLEAN DEFAULT TRUE", "是否允许候补"),
                ("contact_info", "TEXT", "联系方式说明"),
                ("location_name", "VARCHAR(200)", "活动地点名称"),
                ("location_address", "TEXT", "活动地点地址"),
                ("latitude", "FLOAT", "纬度"),
                ("longitude", "FLOAT", "经度"),
                ("requirements", "TEXT", "参与要求"),
                ("notes", "TEXT", "备注信息"),
                ("images", "TEXT", "活动图片"),
                ("view_count", "INT DEFAULT 0", "浏览次数")
            ]
            
            # 添加新字段
            for column_name, column_type, comment in new_columns:
                if column_name not in existing_columns:
                    try:
                        sql = f"ALTER TABLE activities ADD COLUMN {column_name} {column_type} COMMENT '{comment}'"
                        db.session.execute(text(sql))
                        print(f"✓ 添加字段: {column_name}")
                    except Exception as e:
                        print(f"✗ 添加字段 {column_name} 失败: {e}")
                else:
                    print(f"- 字段 {column_name} 已存在")
            
            # 更新status字段的注释（支持新的状态）
            try:
                db.session.execute(text(
                    "ALTER TABLE activities MODIFY COLUMN status VARCHAR(20) DEFAULT 'open' "
                    "COMMENT '状态：open=开放,closed=关闭,cancelled=取消,finished=已结束'"
                ))
                print("✓ 更新status字段注释")
            except Exception as e:
                print(f"✗ 更新status字段失败: {e}")
            
            # 提交更改
            db.session.commit()
            print("\n✅ 活动表升级完成！")
            
            # 显示更新后的表结构
            columns = db.session.execute(text("DESCRIBE activities")).fetchall()
            print("\n更新后的活动表结构:")
            for col in columns:
                print(f"  {col[0]} - {col[1]} - {col[4] or ''}")
            
            return True
            
        except Exception as e:
            db.session.rollback()
            print(f"❌ 升级失败: {e}")
            return False

def main():
    """主函数"""
    print("开始升级活动表结构...")
    success = upgrade_activity_table()
    
    if success:
        print("\n🎉 升级成功！现在活动表支持更丰富的功能：")
        print("- 报名截止时间")
        print("- 最少参与人数")
        print("- 活动类型和标签")
        print("- 费用相关信息")
        print("- 审核和候补设置")
        print("- 联系方式")
        print("- 自定义地点信息")
        print("- 参与要求和备注")
        print("- 活动图片")
        print("- 浏览统计")
    else:
        print("\n❌ 升级失败，请检查错误信息")
        sys.exit(1)

if __name__ == "__main__":
    main() 